<template>
  <div class="app-container falseTabel-container oneSearchNoFooter">
    <div class="customContainer">
      <!-- 搜索头 -->
      <el-form
        :inline="true"
        :model="formInline"
        ref="formInline"
        class="demo-form-inline"
        size="small"
      >
        <el-form-item>
          <el-checkbox
            true-label="1"
            false-label="0"
            v-model="formInline.look_del"
            @change="lookDelChange"
            border
          >查看已删门店</el-checkbox>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            :editable="false"
            :clearable="false"
            v-model="pickerDate"
            value-format="yyyy.MM.dd"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-select filterable placeholder="选择门店" v-model="formInline.store_id">
            <el-option v-for="item in storeList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="choosePerson"
            multiple
            collapse-tags
            placeholder="请选择"
            @change="selectAll"
          >
            <el-option
              v-for="item in selectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <dj-button size="small" @search="searchClick">
            <template #default>搜索</template>
          </dj-button>
        </el-form-item>
      </el-form>
      <el-table
        highlight-current-row
        v-loading.body="listLoading"
        :data="list"
        border
        size="small"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column align="center" prop="name" label="营收分类"></el-table-column>
        <el-table-column align="center" label="种类">
          <template slot-scope="scope">
            <template v-for="(item,index) in scope.row.list">
              <p
                :key="index"
                v-if="item.money*1!=0||item.time*1!=0||scope.row.name=='售币类'"
              >{{item.name}}</p>
            </template>
            <template v-if="scope.row.all_money*1==0&&scope.row.name!='售币类'">-</template>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="all_time" label="笔数">
          <template slot-scope="scope">
            <template v-for="(item,index) in scope.row.list">
              <p
                :key="index"
                v-if="item.money*1!=0||item.time*1!=0||scope.row.name=='售币类'"
              >{{item.time}}</p>
            </template>
            <template v-if="scope.row.all_money*1==0&&scope.row.name!='售币类'">0</template>
          </template>
        </el-table-column>
        <el-table-column align="center" label="笔数占比">
          <template slot-scope="scope">
            <template v-for="(item,index) in scope.row.list">
              <p :key="index" v-if="item.money*1!=0||item.time*1!=0||scope.row.name=='售币类'">
                <span v-if="scope.row.all_time*1==0">0%</span>
                <span v-else>{{(item.time*100/scope.row.all_time*1)|keepTwoNum}}%</span>
              </p>
            </template>
            <template v-if="scope.row.all_time*1==0&&scope.row.name!='售币类'">0%</template>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="all_money" label="金额（元）">
          <template slot-scope="scope">
            <template v-for="(item,index) in scope.row.list">
              <p
                :key="index"
                v-if="item.money*1!=0||item.time*1!=0||scope.row.name=='售币类'"
              >{{item.money|keepTwoNum}}</p>
            </template>
            <template v-if="scope.row.all_money*1==0&&scope.row.name!='售币类'">0.00</template>
          </template>
        </el-table-column>
        <el-table-column align="center" label="金额占比">
          <template slot-scope="scope">
            <template v-for="(item,index) in scope.row.list">
              <p :key="index" v-if="item.money*1!=0||item.time*1!=0||scope.row.name=='售币类'">
                <span v-if="scope.row.all_money*1==0">0%</span>
                <span v-else>{{(item.money*100/scope.row.all_money*1)|keepTwoNum}}%</span>
              </p>
            </template>
            <template v-if="scope.row.all_money*1==0&&scope.row.name!='售币类'">0%</template>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="all_money" label="金额合计（元）"></el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import {
  getList,
  getStoreList,
} from "@/api/storage_control/revenueAnalysis_all_form";
import { pickerOptionsF, pickerDateF, optionMaxTime } from "@/utils";
export default {
  data() {
    return {
      selectOptions: [
        { value: "0", label: "全部分类" },
        { value: "1", label: "售币类" },
        { value: "2", label: "门禁类" },
        { value: "3", label: "其他类" },
      ],
      oldOptions: [],
      choosePerson: ["0", "1", "2", "3"],
      listLoading: false,
      storeList: null,
      typeList: [],
      formInline: {
        begin_time: "",
        end_time: "",
        store_id: "",
        type: [],
        look_del: "0",
      },
      storeId: "",
      list: [],
      total: {},
      pickerOptions: pickerOptionsF(-1),
      pickerDate: pickerDateF(-1, -1),
    };
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      if (!vm.storeList) {
        vm.getStore();
      }
    });
  },
  methods: {
    lookDelChange() {
      this.getStore();
    },
    selectAll(val) {
      const allValues = [];
      // 保留所有值
      for (const item of this.selectOptions) {
        allValues.push(item.value);
      }
      // 用来储存上一次的值，可以进行对比
      const oldVal = this.oldOptions.length === 1 ? this.oldOptions[0] : [];

      // 若是全部选择
      if (val.includes("0")) this.choosePerson = allValues;

      // 取消全部选中 上次有 当前没有 表示取消全选
      if (oldVal.includes("0") && !val.includes("0")) this.choosePerson = [];

      // 点击非全部选中 需要排除全部选中 以及 当前点击的选项
      // 新老数据都有全部选中
      if (oldVal.includes("0") && val.includes("0")) {
        const index = val.indexOf("0");
        val.splice(index, 1); // 排除全选选项
        this.choosePerson = val;
      }

      // 全选未选 但是其他选项全部选上 则全选选上 上次和当前 都没有全选
      if (!oldVal.includes("0") && !val.includes("0")) {
        if (val.length === allValues.length - 1)
          this.choosePerson = ["0"].concat(val);
      }
      // 储存当前最后的结果 作为下次的老数据
      this.oldOptions[0] = this.choosePerson;
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "合计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (index > 0) {
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = (sums[index] * 1).toFixed(2) * 1;
          } else {
            sums[index] = "-";
          }
        }
      });
      return sums;
    },
    getStore() {
      getStoreList({
        look_del: this.formInline.look_del,
        category_id: 278,
      }).then((response) => {
        this.storeList = response;
        if (this.storeId) {
          //console.log(this.storeId,111)
          this.formInline.store_id = this.storeId;
          this.searchClick();
        } else {
          //console.log(this.storeId,222)
          let data = response.filter(
            (res) => res.id == this.$store.getters.optionId
          );
          if (data.length > 0) {
            this.formInline.store_id = data[0].id;
          } else {
            if (this.storeList.length > 0) {
              this.formInline.store_id = this.storeList[0].id;
            }
          }
          this.storeChange();
        }
      });
    },
    storeChange() {
      this.searchClick();
    },
    searchClick() {
      optionMaxTime(this.pickerDate).then(() => {
        //最大可选择时间区间
        this.formInline.begin_time = this.pickerDate ? this.pickerDate[0] : "";
        this.formInline.end_time = this.pickerDate ? this.pickerDate[1] : "";
        this.formInline.type =
          this.choosePerson.indexOf("0") != -1
            ? JSON.parse(JSON.stringify(this.choosePerson)).splice(1)
            : this.choosePerson;
        this.fetchData();
      });
    },
    // 列表获取
    fetchData() {
      this.listLoading = true;
      getList(this.formInline)
        .then((response) => {
          this.listLoading = false;
          this.list = response;
        })
        .catch((res) => {
          this.listLoading = false;
        });
    },
    getStoreId() {
      //this.formInline.store_id=this.$route.params.store_id;
      if (this.$route.params.store_id) {
        this.storeId = this.$route.params.store_id;
        //console.log(this.$route.params.store_id,333)
        this.getStore();
      }
      //console.log(this.storeId)
    },
  },
  activated() {
    this.getStoreId();
  },
};
</script>